<?php

/**
 * @param $params
 * @param string $return
 * @return array
 */
function product($params, $return = 'mixed')
{
    $doc = "\n" . '    /**' . "\n";

    $request = function ($key, $param) {
        $accept = '        ';
        $name = '\'' . $key . '\'';
        $accept .= '$' . $key . ' = ';
        if ($param) {
            $accept .= 'Request::instance()->param(' . $name . ',\'' . $param . '\')';
        } else {
            $accept .= 'Request::instance()->param(' . $name . ')';
        }
        $accept .= ";\n";

        return $accept;
    };

    $accept = '';
    $input_param = '';

    if ($params) {
        foreach ($params as $key => $param) {

            if (empty($key)) {
                continue;
            }

            /**
             * 处理接受的参数信息
             */
            $accept .= $request($key, $param);

            if (preg_match('/[0-9]/', $param)) {
                $type = 'int';
            } else {
                $type = 'string';
            }

            $doc .= '     * @param ' . $type . ' $' . $key . "\n";

            $input_param .= '$' . $key . ', ';
        }
    }

    $doc .= '     * @return ' . $return . "\n";
    $doc .= '     */';

    $input_param = trim($input_param, ', ');

    return [
        'doc' => $doc,
        'accept' => trim($accept),
        'input_param' => $input_param
    ];
}

/**
 * @param string $file_path 要追加的
 * @param string $template
 * @return bool
 */
function append($file_path, $template)
{
    if (!is_file($file_path)) {
        return false;
    }

    preg_match('/function ([\w]+)/', $template, $matches);

    $action = isset($matches[1]) ? $matches[1] : '';

    if (empty($action)) {
        return false;
    }

    $content = file_get_contents($file_path);

    if (preg_match('/' . $action . '()/', $content)) {
        return true;
    }

    $content .= '}';

    $content = str_replace('}}', $template . "\n" . '}', $content);

    if (file_put_contents($file_path, $content)) {
        return true;
    }

    return false;
}
